<template>
  <el-form-item :label="label">
    <el-progress
      v-if="isUploading"
      type="circle"
      :percentage="percentage"
      :status="percentage === 100 ? 'success' : undefined">
    </el-progress>
    <el-upload
      v-else
      class="avatar-uploader"
      action="#"
      :http-request="handleUpload"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <!-- img为预览图片显示 -->
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </el-form-item>
</template>

<script>
import { updtaCourseImage } from '@/services/course'
export default {
  props: {
    value: {
      type: String
    },
    label: {
      type: String
    },
    limitM: {
      type: Number,
      default: 2
    }
  },
  name: 'CourseImage',
  data () {
    return {
      isUploading: false,
      percentage: 0
    }
  },
  methods: {
    //  图片上传自定义方法
    // 上传文件相关信息option
    // option.file为要上传的图片信息
    async handleUpload (option) {
      this.isUploading = true
      // 需要使用FormData对象处理
      const fd = new FormData()
      fd.append('file', option.file)
      const { data } = await updtaCourseImage(fd, event => {
        this.percentage = Math.floor(event.loaded / event.total) * 100
      })
      if (data.code === '000000') {
        // this.course.courseListImg = data.data.name
        this.$emit('input', data.data.name)
        this.isUploading = false
        this.percentage = 0
      }
    },
    //  图片上传成功后的回调
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    //  图片上传前的回调
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < this.limitM

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 200MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped >
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
